package com.franklin.ideaplugin.easytesting.ui.pressuretest;

import cn.hutool.core.util.NumberUtil;
import com.franklin.ideaplugin.api.ui.IBaseComponent;
import com.franklin.ideaplugin.easytesting.cache.IEasyTestingCache;
import com.franklin.ideaplugin.easytesting.entity.PressureTestConfig;
import com.intellij.openapi.project.Project;

import javax.swing.*;
import java.util.Objects;

/**
 * @author Ye Junhui
 * @since 2023/11/3
 */
public class PressureTestForm implements IBaseComponent {
    private JPanel mainPanel;
    private JTextField threadCountTextField;
    private JTextField rampUpPeriodTextField;
    private JTextField loopCountTextField;
    private JTextField durationTextField;

    private final Project project;

    public PressureTestForm(Project project) {
        this.project = project;
        this.init();
    }

    /**
     * 初始化
     */
    private void init() {
        IEasyTestingCache easyTestingCache = IEasyTestingCache.getInstance(this.project);
        PressureTestConfig pressureTestConfig = easyTestingCache.getThreadPoolConfig();
        this.threadCountTextField.setText(Objects.nonNull(pressureTestConfig.getThreadCount()) ? pressureTestConfig.getThreadCount().toString() : "10");
        this.rampUpPeriodTextField.setText(Objects.nonNull(pressureTestConfig.getRampUpPeriod()) ? pressureTestConfig.getRampUpPeriod().toString() : "1");
        this.loopCountTextField.setText(Objects.nonNull(pressureTestConfig.getLoopCount()) ? pressureTestConfig.getLoopCount().toString() : "100");
        this.durationTextField.setText(Objects.nonNull(pressureTestConfig.getDuration()) ? pressureTestConfig.getDuration().toString() : "120");
    }

    @Override
    public JComponent getMainPanel() {
        return this.mainPanel;
    }

    /**
     * 获取
     * @return
     */
    public PressureTestConfig getThreadPoolConfig(){
        //新值
        PressureTestConfig pressureTestConfig = new PressureTestConfig();
        pressureTestConfig.setThreadCount(NumberUtil.parseInt(this.threadCountTextField.getText()));
        pressureTestConfig.setRampUpPeriod(NumberUtil.parseLong(this.rampUpPeriodTextField.getText()));
        pressureTestConfig.setLoopCount(NumberUtil.parseInt(this.loopCountTextField.getText()));
        pressureTestConfig.setDuration(NumberUtil.parseLong(this.durationTextField.getText()));

        //缓存
        IEasyTestingCache easyTestingCache = IEasyTestingCache.getInstance(this.project);
        easyTestingCache.cacheThreadPoolConfig(pressureTestConfig);

        return pressureTestConfig;
    }
}
